﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web.Security;
using System.Configuration;
using System.Data;
using BoardPACDSDAO.Auth;
using BoardPACUtil.Util;
using BoardPACDSDAO.Entity;
using BoardPACDSBO.UserMgt;
using BoardPACDSBO.Auth;
using BoardPACDSBO.General;
using BoardPACDSBO.Admin;

namespace BoardPACDSDAO.LogOn
{
    public class LogOnDAO
    {
        AccountMembershipService MembershipService = new AccountMembershipService();

        public Guid GetUserGuid(string userName)
        {
            Guid output = new Guid();
            try
            {
                output = (Guid)(Membership.GetUser(userName).ProviderUserKey);
            }
            catch (GenServiceException)
            {
                throw;
            }
            catch (Exception)
            {
                throw;
            }
            return output;
        }

        public byte? GetUserGuid(string deviceId, string macAddress)
        {
            try
            {
                if (deviceId != null || macAddress != null)
                {
                    using (BoardAppProductEntities entities = DataObjectFactory.CreateContext())
                    {
                        Device device = null;

                        if (deviceId != null)
                        {
                            device = (from ud in entities.Devices
                                      where (ud.DeviceId.Equals(deviceId.Trim()))
                                      select ud).FirstOrDefault();
                        }

                        if (macAddress != null && device == null)
                        {
                            device = (from ud in entities.Devices
                                      where (ud.MacAddress.Equals(macAddress.Trim()))
                                      select ud).FirstOrDefault();
                        }

                        if (device == null) // Not registered yet.
                            throw new GenServiceException("err_152");

                        if (device.Status == (byte)DeviceStatus.Wipeout) // device is in wipeout status
                            throw new GenServiceException("err_155");

                        if (device.Status != (byte)DeviceStatus.Active) // device is in deactivate status
                            throw new GenServiceException("err_153");
                    }
                }
                else
                {
                    throw new GenServiceException("err_151");
                }
            }
            catch (Exception)
            {
                throw;
            }
            return null;
        }

        public bool ValidateUser(string userName, string password)
        {
            try
            {
                return MembershipService.ValidateUser(userName, password);
            }
            catch (GenServiceException)
            {
                throw;
            }
            catch (Exception)
            {
                throw new GenServiceException("err_109");
            }
        }

        public bool IsIPadAllowed(LogOnModel model, RequestHeader request, string format)
        {
            try
            {
                using (BoardAppProductEntities entities = DataObjectFactory.CreateContext())
                {
                    List<Guid> iPadAllowedRoleIds = new List<Guid> { ApplicationConstants.ORGANIZER, ApplicationConstants.MEMBER };

                    return (from u in entities.Users
                            join ur in entities.aspnet_UsersInRoles on u.UserId equals ur.UserId
                            join r in entities.aspnet_Roles on ur.RoleId equals r.RoleId
                            where u.UserName.Equals(model.UserName) && iPadAllowedRoleIds.Contains(r.RoleId)
                            select u).Count() > 0;
                }
            }
            catch (GenServiceException)
            {
                throw;
            }
            catch (SqlException)
            {
                throw new GenServiceException("err_105");
            }
            catch (Exception)
            {
                throw new GenServiceException("err_109");
            }
        }

        public UserMgtModelsMetadata GetUser(string userName)
        {
            try
            {
                using (BoardAppProductEntities entities = DataObjectFactory.CreateContext())
                {
                    UserMgtModelsMetadata user = (from u in entities.Users
                                                  where u.UserName == userName
                                                  select new UserMgtModelsMetadata()
                                                  {
                                                      displayName = u.DisplayName,
                                                      customUserId = u.CustomUserId,
                                                      email = u.BoardEmail,
                                                      firstName = u.FirstName,
                                                      lastname = u.LastName,
                                                      mobileno = u.MobileNumber,
                                                      modifiedBy = u.ModifiedBy.HasValue ? u.ModifiedBy.Value : 0,
                                                      officeEmail = u.OfficeEmail,
                                                      officeno = u.OfficePhone,
                                                      saluation = u.Title,
                                                      username = u.UserName,
                                                      userStatus = u.Status,
                                                      passwordReseted = u.PasswordReseted
                                                  }).FirstOrDefault();

                    user.roleName = Roles.GetRolesForUser(userName).FirstOrDefault();

                    return user;
                }
            }
            catch (GenServiceException)
            {
                throw;
            }
            catch (Exception)
            {
                throw new GenServiceException("err_109");
            }
        }

        public List<UserRole> GetUserRoles(List<string> userRoles)
        {
            try
            {
                using (BoardAppProductEntities entities = DataObjectFactory.CreateContext())
                {
                    return (from r in entities.aspnet_Roles
                            where userRoles.Contains(r.RoleName)
                            select new UserRole()
                            {
                                RoleActions = r.Description,
                                RoleID = r.RoleId,
                                RoleDisplayName = r.RoleName
                            }).ToList();
                }
            }
            catch (GenServiceException)
            {
                throw;
            }
            catch (Exception)
            {
                throw new GenServiceException("err_109");
            }
        }

        public List<RoleOfUser> GetRoleOfUser(int userId)
        {
            try
            {
                using (BoardAppProductEntities entities = DataObjectFactory.CreateContext())
                {
                    return (from a in entities.Accesses
                            where a.CustomUserId == userId
                            select new RoleOfUser()
                            {
                                RoleActions = a.aspnet_Roles.Description,
                                RoleDisplayName = a.aspnet_Roles.RoleName
                            }).ToList();
                }
            }
            catch (GenServiceException)
            {
                throw;
            }
            catch (Exception)
            {
                throw new GenServiceException("err_109");
            }
        }

        public void IsDeviceAllowed(string deviceId, string macAddress)
        {
            if (deviceId != null || macAddress != null)
            {
                using (BoardAppProductEntities entities = DataObjectFactory.CreateContext())
                {
                    Device device = null;

                    if (deviceId != null)
                    {
                        device = (from ud in entities.Devices
                                  where (ud.DeviceId.Equals(deviceId.Trim()))
                                  select ud).FirstOrDefault();
                    }

                    if (macAddress != null && device == null)
                    {
                        device = (from ud in entities.Devices
                                  where (ud.MacAddress.Equals(macAddress.Trim()))
                                  select ud).FirstOrDefault();
                    }

                    if (device == null) // Not registered yet.
                        throw new GenServiceException("err_152");

                    if (device.Status == (byte)DeviceStatus.Wipeout) // device is in wipeout status
                        throw new GenServiceException("err_155");

                    if (device.Status != (byte)DeviceStatus.Active) // device is in deactivate status
                        throw new GenServiceException("err_153");
                }
            }
            else
            {
                throw new GenServiceException("err_151");
            }
        }

        public int GetRegisteredDiviceCount(RequestHeader request)
        {
            try
            {
                using (BoardAppProductEntities entities = DataObjectFactory.CreateContext())
                {
                    return (from ud in entities.Devices
                            where ((ud.DeviceId.Equals(request.deviceId) || ud.MacAddress.Equals(request.macAddress)) && ud.Status == (byte)DeviceStatus.Active /*ud.Status == true*/)
                            select ud).Count();
                }
            }
            catch (GenServiceException)
            {
                throw;
            }
            catch (Exception)
            {
                throw new GenServiceException("err_109");
            }
        }

        public MemberModel GetMembershipUser(string userName)
        {
            try
            {
                MembershipUser user = Membership.GetUser(userName);
                return new MemberModel()
                {
                    Comment = user.Comment,
                    CreationDate = user.CreationDate,
                    Email = user.Email,
                    IsApproved = user.IsApproved,
                    LastActivityDate = user.LastActivityDate,
                    LastLockoutDate = user.LastLockoutDate,
                    LastLoginDate = user.LastLoginDate,
                    LastPasswordChangedDate = user.LastPasswordChangedDate,
                    IsLockedOut = user.IsLockedOut,
                    IsOnline = user.IsOnline,
                    PasswordQuestion = user.PasswordQuestion,
                    ProviderName = user.ProviderName,
                    ProviderUserKey = user.ProviderUserKey,
                    UserName = user.UserName
                };
            }
            catch (GenServiceException)
            {
                throw;
            }
            catch (Exception)
            {
                throw new GenServiceException("err_109");
            }
        }

        public MembershipServiceModel GetMembershipService()
        {
            try
            {
                return new MembershipServiceModel()
                {
                    MinNonAlphanumericCharacters = MembershipService.MinNonAlphanumericCharacters,
                    MinPasswordLength = MembershipService.MinPasswordLength
                };
            }
            catch (GenServiceException)
            {
                throw;
            }
            catch (Exception)
            {
                throw new GenServiceException("err_109");
            }
        }

        public bool UnlockUser(string userName)
        {
            MembershipUser mUser = Membership.GetUser(userName);
            try
            {
                if (mUser != null)
                {
                    if (mUser.IsLockedOut)
                    {
                        if (mUser.LastLockoutDate.AddMinutes(30) <= DateTime.Now)
                        {
                            mUser.UnlockUser();
                        }
                        throw new GenServiceException("err_103");
                    }
                }
                return mUser.CreationDate == mUser.LastPasswordChangedDate;
            }
            catch (GenServiceException)
            {
                throw;
            }
            catch (Exception)
            {
                throw new GenServiceException("err_111_sys");
            }
        }
    }
}
